package cn.iocoder.yudao.module.contract.controller.admin.invoiceContract;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.module.contract.dal.dataobject.invoice.InvoiceDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.contract.service.invoice.InvoiceService;
import cn.iocoder.yudao.module.contract.utils.FileDownloadUtil;
import cn.iocoder.yudao.module.contract.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.NOT_IMPLEMENTED;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.contract.controller.admin.invoiceContract.vo.*;
import cn.iocoder.yudao.module.contract.dal.dataobject.invoiceContract.InvoiceContractDO;
import cn.iocoder.yudao.module.contract.service.invoiceContract.InvoiceContractService;

@Tag(name = "管理后台 - 发票合同")
@RestController
@RequestMapping("/contract/invoice-contract")
@Validated
public class InvoiceContractController {

    @Resource
    private InvoiceContractService invoiceContractService;
    @Resource
    private InvoiceService invoiceService;

    @PostMapping("/create")
    @Operation(summary = "创建发票合同")
    @PreAuthorize("@ss.hasPermission('contract:invoice-contract:create')")
    public CommonResult<Long> createInvoiceContract(@Valid @RequestBody InvoiceContractSaveReqVO createReqVO) {
        return success(invoiceContractService.createInvoiceContract(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新发票合同")
    @PreAuthorize("@ss.hasPermission('contract:invoice-contract:update')")
    public CommonResult<Boolean> updateInvoiceContract(@Valid @RequestBody InvoiceContractSaveReqVO updateReqVO) {
        invoiceContractService.updateInvoiceContract(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除发票合同")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('contract:invoice-contract:delete')")
    public CommonResult<Boolean> deleteInvoiceContract(@RequestParam("id") Long id) {
        invoiceContractService.deleteInvoiceContract(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得发票合同")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('contract:invoice-contract:query')")
    public CommonResult<InvoiceContractRespVO> getInvoiceContract(@RequestParam("id") Long id) {
        InvoiceContractDO invoiceContract = invoiceContractService.getInvoiceContract(id);
        return success(BeanUtils.toBean(invoiceContract, InvoiceContractRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得发票合同分页")
    @PreAuthorize("@ss.hasPermission('contract:invoice-contract:query')")
    public CommonResult<PageResult<InvoiceContractRespVO>> getInvoiceContractPage(@Valid InvoiceContractPageReqVO pageReqVO) {
        PageResult<InvoiceContractPageRespVO> pageResult = invoiceContractService.getInvoiceContractPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, InvoiceContractRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出发票合同 Excel")
    @PreAuthorize("@ss.hasPermission('contract:invoice-contract:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportInvoiceContractExcel(@Valid InvoiceContractPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<InvoiceContractPageRespVO> list = invoiceContractService.getInvoiceContractPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "发票合同.xls", "数据", InvoiceContractExportVO.class,
                        BeanUtils.toBean(list, InvoiceContractExportVO.class));
    }

    @GetMapping("/getDetails")
    @Operation(summary = "获得发票合同")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<?> getDetails(@RequestParam("id") Long id) {
        InvoiceContractDO invoiceContract = invoiceContractService.getInvoiceContract(id);
        List<InvoiceDO> invoiceList = invoiceService.list(new LambdaQueryWrapper<InvoiceDO>().in(InvoiceDO::getId,Arrays.asList(invoiceContract.getInvoiceIds().split(","))));
        Map<String,Object> data = new HashMap<>();
        data.put("invoiceContract",invoiceContract);
        data.put("invoiceList",invoiceList);
        return success(data);
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download")
    public ResponseEntity<?> download(String ids) throws UnsupportedEncodingException {
        String[] id = ids.split(",");
        if (id.length == 1) {
            //单文件下载
            InvoiceContractDO invoiceContract = invoiceContractService.getById(id[0]);
            invoiceContract.setDownloadCount(invoiceContract.getDownloadCount() + 1);
            invoiceContractService.updateById(invoiceContract);
            String fileNmae = invoiceContract.getClientCode()+invoiceContract.getGfmc()+invoiceContract.getCompanyid()+invoiceContract.getContractNo()+invoiceContract.getQyusername();
            return FileDownloadUtil.downloadFile(invoiceContract.getContractFileUrl(), URLEncoder.encode(fileNmae,"UTF-8") );
        } else if (id.length > 1) {
            //批量下载
            List<InvoiceContractDO> list = invoiceContractService.list(Wrappers.<InvoiceContractDO>lambdaQuery().in(InvoiceContractDO::getId, id));
            List<String> fileUrls = new ArrayList<>();
            List<String> fileNames = new ArrayList<>();
            for (InvoiceContractDO invoiceContract : list) {
                fileUrls.add(invoiceContract.getContractFileUrl());
                String fileNmae = invoiceContract.getClientCode()+invoiceContract.getGfmc()+invoiceContract.getCompanyid()+invoiceContract.getContractNo()+invoiceContract.getQyusername();
                fileNames.add(fileNmae);
//                fileNames.add(orderDO.getVbeln()+orderDO.getKname()+orderDO.getVkorg()+orderDO.getYwyt());
            }
            invoiceContractService.update(Wrappers.<InvoiceContractDO>update().setSql(" download_count = download_count + 1").in("id", id));
            return FileDownloadUtil.downloadZip(fileUrls, fileNames);
        } else {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "请选择要下载的合同");

        }
    }

    /**
     * 合同打印计数
     */
    @GetMapping("/prints")
    public CommonResult<?> prints(String ids) {
        String[] id = ids.split(",");
        if (id.length != 0) {
            invoiceContractService.update(Wrappers.<InvoiceContractDO>update().setSql(" print_count = print_count + 1").in("id", id));
            return success("操作成功");
        } else {
            return CommonResult.error(NOT_IMPLEMENTED);
        }
    }

    @GetMapping("/cancellation")
    @Operation(summary = "作废")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<?> cancellation(@RequestParam("id") Long id) {
        InvoiceContractDO invoiceContract = invoiceContractService.getInvoiceContract(id);
        if(invoiceContract==null){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"发票合同不存在");
        }
        List<InvoiceDO> invoiceList = invoiceService.list(new LambdaQueryWrapper<InvoiceDO>().eq(InvoiceDO::getContractId,invoiceContract.getId()));
        invoiceContractService.cancellation(invoiceContract,invoiceList);
        invoiceService.invoiceStatusPush(invoiceList,"2");
        return success(true);

    }
    @GetMapping("/generateContractFile")
    @Operation(summary = "合同生成")
    public CommonResult<Boolean> generateContractFile(String id) {
        InvoiceContractDO invoiceContract = invoiceContractService.getById(id);
        if (invoiceContract == null) {
            return error("合同不存在");
        }
        List<InvoiceDO> invoiceList = invoiceService.list(new LambdaQueryWrapper<InvoiceDO>().eq(InvoiceDO::getContractId,invoiceContract.getId()));
        invoiceContractService.generateContractFile(invoiceContract,invoiceList,"1");
        invoiceContractService.updateById(invoiceContract);
        if (!"1".equals(invoiceContract.getStatus())) {
            return error(invoiceContract.getAbnormalCause());
        }
        return success(true);
    }


    @PutMapping("/fileUpload")
    @Operation(summary = "合同上传")
    public CommonResult<Boolean> fileUpload(@Valid @RequestBody InvoiceContractSaveReqVO updateReqVO) {
//        if (StringUtils.isBlank(updateReqVO.getFileIds()) && StringUtils.isBlank(updateReqVO.getScanFileIds()) ) {
//            return error("请上传文件");
//        }
        InvoiceContractDO invoiceContract = invoiceContractService.getById(updateReqVO.getId());
        if(invoiceContract==null){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"发票合同不存在");
        }
        InvoiceContractDO updateObj = BeanUtils.toBean(updateReqVO, InvoiceContractDO.class);
        invoiceContractService.updateById(updateObj);
        return success(true);
    }

}